package com.ruoyi.business.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.business.domain.ExtInterfaceParameter;
import com.ruoyi.business.domain.ExtInterfaceParameterRela;
import com.ruoyi.business.mapper.ExtInterfaceParameterRelaMapper;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.ExtInterfaceParameterMapper;
import com.ruoyi.business.domain.ExtInterfaceParameter;
import com.ruoyi.business.service.IExtInterfaceParameterService;

/**
 * 接口参数Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-22
 */
@Service
public class ExtInterfaceParameterServiceImpl implements IExtInterfaceParameterService
{
    @Autowired
    private ExtInterfaceParameterMapper extInterfaceParameterMapper;
    @Autowired
    private ExtInterfaceParameterRelaMapper extInterfaceParameterRelaMapper;
    /**
     * 查询接口参数
     *
     * @param id 接口参数主键
     * @return 接口参数
     */
    @Override
    public ExtInterfaceParameter selectExtInterfaceParameterById(Long id)
    {
        return extInterfaceParameterMapper.selectExtInterfaceParameterById(id);
    }

    /**
     * 查询接口参数列表
     *
     * @param extInterfaceParameter 接口参数
     * @return 接口参数
     */
    @Override
    public List<ExtInterfaceParameter> selectExtInterfaceParameterList(ExtInterfaceParameter extInterfaceParameter)
    {
        return extInterfaceParameterMapper.selectExtInterfaceParameterList(extInterfaceParameter);
    }

    /**
     * 新增接口参数
     *
     * @param extInterfaceParameter 接口参数
     * @return 结果
     */
    @Override
    public int insertExtInterfaceParameter(ExtInterfaceParameter extInterfaceParameter)
    {
        //新增校验
        checkInsert(extInterfaceParameter);
        int row =  extInterfaceParameterMapper.insertExtInterfaceParameter(extInterfaceParameter);
        //同时插入接口参数关系表
        ExtInterfaceParameterRela rela = new ExtInterfaceParameterRela();
        rela.setExtInterfaceParameterId(extInterfaceParameter.getId());
        rela.setInterfaceCode(extInterfaceParameter.getInterfaceCode());
        rela.setCreateTime(DateUtils.getNowDate());
        rela.setCreateBy(SecurityUtils.getUsername());
        rela.setEnterpriseCode(extInterfaceParameter.getEnterpriseCode());
        rela.setApplicationCode(extInterfaceParameter.getApplicationCode());
        extInterfaceParameterRelaMapper.insertExtInterfaceParameterRela(rela);
        return row;
    }

    /**
     * 插入前校验
     * @param extInterfaceParameter
     */
    private void checkInsert(ExtInterfaceParameter extInterfaceParameter) {
        if(extInterfaceParameter==null)
            throw new ServiceException("插入对象为空!");
        //接口编码不能为空
        if(StringUtils.isEmpty(extInterfaceParameter.getInterfaceCode()))
            throw new ServiceException("接口编码不能为空!");
        //参数名称不能为空
        if(StringUtils.isEmpty(extInterfaceParameter.getParameterName()))
            throw new ServiceException("参数名称不能为空!");
        //参数名称在同一个接口不能重复
        Map<String,Object> searchMap = new HashMap<>();
        searchMap.put("parameterName",extInterfaceParameter.getParameterName());
        searchMap.put("interfaceCode",extInterfaceParameter.getInterfaceCode());
        if(extInterfaceParameterMapper.selectCount(searchMap)>0)
            throw new ServiceException("在同一个接口下参数名称："+extInterfaceParameter.getParameterName()+"已经存在!");
        //参数描述不能为空
        if(StringUtils.isEmpty(extInterfaceParameter.getParameterDesc()))
            throw new ServiceException("参数描述不能为空");
        //参数描述在同一个接口不能重复
        searchMap.clear();
        searchMap.put("parameterDesc",extInterfaceParameter.getParameterDesc());
        searchMap.put("interfaceCode",extInterfaceParameter.getInterfaceCode());
        if(extInterfaceParameterMapper.selectCount(searchMap)>0)
            throw new ServiceException("在同一个接口下参数描述："+extInterfaceParameter.getParameterDesc()+"已经存在!");
        //参数类型不能为空
        if(StringUtils.isEmpty(extInterfaceParameter.getParameterType()))
            throw new ServiceException("参数类型不能为空!");
        //父级id不为空时，必须存在
        if(extInterfaceParameter.getParentId()!=null && extInterfaceParameter.getParentId()!=0L){
            searchMap.clear();
            searchMap.put("id",extInterfaceParameter.getParentId());
            if(extInterfaceParameterMapper.selectCount(searchMap)==0)
                throw new ServiceException("无效父级id:"+extInterfaceParameter.getParentId());
        }
    }

    /**
     * 修改接口参数
     *
     * @param extInterfaceParameter 接口参数
     * @return 结果
     */
    @Override
    public int updateExtInterfaceParameter(ExtInterfaceParameter extInterfaceParameter)
    {
        //更新校验
        checkUpdate(extInterfaceParameter);
        return extInterfaceParameterMapper.updateExtInterfaceParameter(extInterfaceParameter);
    }

    /**
     * 更新前校验
     * @param extInterfaceParameter
     */
    private void checkUpdate(ExtInterfaceParameter extInterfaceParameter) {
        if(extInterfaceParameter==null)
            throw new ServiceException("更新对象为空!");
        if(extInterfaceParameter.getId()==null||extInterfaceParameter.getId()==0L)
            throw new ServiceException("更新对象id为空!");
        //接口编码不能为空
        if(StringUtils.isEmpty(extInterfaceParameter.getInterfaceCode()))
            throw new ServiceException("接口编码不能为空!");
        //参数名称不能为空
        if(StringUtils.isEmpty(extInterfaceParameter.getParameterName()))
            throw new ServiceException("参数名称不能为空!");
        //参数名称在同一个接口不能重复
        Map<String,Object> searchMap = new HashMap<>();
        searchMap.put("parameterName",extInterfaceParameter.getParameterName());
        searchMap.put("interfaceCode",extInterfaceParameter.getInterfaceCode());
        searchMap.put("notId",extInterfaceParameter.getId());
        if(extInterfaceParameterMapper.selectCount(searchMap)>0)
            throw new ServiceException("在同一个接口下参数名称："+extInterfaceParameter.getParameterName()+"已经存在!");
        //参数描述不能为空
        if(StringUtils.isEmpty(extInterfaceParameter.getParameterDesc()))
            throw new ServiceException("参数描述不能为空");
        //参数描述在同一个接口不能重复
        searchMap.clear();
        searchMap.put("parameterDesc",extInterfaceParameter.getParameterDesc());
        searchMap.put("interfaceCode",extInterfaceParameter.getInterfaceCode());
        searchMap.put("notId",extInterfaceParameter.getId());
        if(extInterfaceParameterMapper.selectCount(searchMap)>0)
            throw new ServiceException("在同一个接口下参数描述："+extInterfaceParameter.getParameterDesc()+"已经存在!");
        //参数类型不能为空
        if(StringUtils.isEmpty(extInterfaceParameter.getParameterType()))
            throw new ServiceException("参数类型不能为空!");
        //父级id不为空时，必须存在
        if(extInterfaceParameter.getParentId()!=null && extInterfaceParameter.getParentId()!=0L){
            searchMap.clear();
            searchMap.put("id",extInterfaceParameter.getParentId());
            if(extInterfaceParameterMapper.selectCount(searchMap)==0)
                throw new ServiceException("无效父级id:"+extInterfaceParameter.getParentId());
        }
    }

    /**
     * 批量删除接口参数
     *
     * @param ids 需要删除的接口参数主键
     * @return 结果
     */
    @Override
    public int deleteExtInterfaceParameterByIds(Long[] ids)
    {
        int sum =0;
        for(Long id:ids){
            sum +=deleteExtInterfaceParameterById(id);
        }
        return sum;
    }

    /**
     * 删除接口参数信息
     *
     * @param id 接口参数主键
     * @return 结果
     */
    @Override
    public int deleteExtInterfaceParameterById(Long id)
    {
        //检查是否有下级依赖
        Map<String,Object> searchMap = new HashMap<>();
        searchMap.put("parentId",id);
        if(extInterfaceParameterMapper.selectCount(searchMap)>0)
            throw new ServiceException("存在下级依赖，不允许删除!");

        //根据参数id，删除接口参数关系表
        extInterfaceParameterRelaMapper.deleteByParameterId(id);
        return extInterfaceParameterMapper.deleteExtInterfaceParameterById(id);
    }

    /**
     * 根据查询条件，返回一颗树列表
     *
     * @param extInterfaceParameter
     * @return
     */
    @Override
    public List<ExtInterfaceParameter> selectTree(ExtInterfaceParameter extInterfaceParameter) {
        //根据条件查询返回列表
        List <ExtInterfaceParameter> results = extInterfaceParameterMapper.selectExtInterfaceParameterList(extInterfaceParameter);
        //构造树列表
        List<ExtInterfaceParameter> treeList = buildTree(results);
        return treeList;
    }
    /**
     * 构造功能树
     * @param list
     * @return
     */
    private List<ExtInterfaceParameter> buildTree(List<ExtInterfaceParameter> list) {
        List<ExtInterfaceParameter> retList = new ArrayList<>();

        //循环构造第一级
        for(ExtInterfaceParameter interfaceParameter:list){
            if(interfaceParameter.getParentId()==null||interfaceParameter.getParentId()==0L){
                retList.add(recursionMakeTreeNode(interfaceParameter,list));
            }
        }
        return retList;
    }

    /**
     * 递归构造当前节点及下级节点
     * @param interfaceParameter
     * @param list
     * @return
     */
    private ExtInterfaceParameter recursionMakeTreeNode(ExtInterfaceParameter interfaceParameter, List<ExtInterfaceParameter> list) {
        //获取直接下级
        List<ExtInterfaceParameter> childList = list.stream().filter(item->interfaceParameter.getId().equals(item.getParentId())).collect(Collectors.toList());
        interfaceParameter.setChildren(childList);
        //递归下级
        for(ExtInterfaceParameter child:childList){
            recursionMakeTreeNode(child,list);
        }
        return interfaceParameter;
    }
}
